package com.dyzx.hbb.modules.fcxs.controller;

import cn.hutool.core.bean.BeanUtil;
import com.dyzx.hbb.common.base.Result;
import com.dyzx.hbb.common.config.MyLambdaQueryWrapper;
import com.dyzx.hbb.common.controller.BaseValidController;
import com.dyzx.hbb.common.utils.Utils;
import com.dyzx.hbb.modules.fcxs.entity.FcxsHouse;
import com.dyzx.hbb.modules.fcxs.entity.FcxsOrder;
import com.dyzx.hbb.modules.fcxs.query.FcxsOrderQuery;
import com.dyzx.hbb.modules.fcxs.service.*;
import com.dyzx.hbb.modules.fcxs.vo.FcxsOrderUVO;
import com.dyzx.hbb.modules.fcxs.vo.FcxsOrderVO;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.Map;

/**
 * 订单管理控制器
 * 
 * 功能说明：负责处理房地产销售系统中订单信息的创建、查询、更新和删除等操作
 * 主要职责：
 * - 提供订单信息的CRUD接口
 * - 支持按条件查询订单列表
 * - 实现订单编号的自动生成
 * - 关联房屋、客户、财务、优惠等相关信息
 * - 计算订单的各项金额（折扣、收支、剩余金额等）
 * 
 * @author 开发团队
 * @version 1.0.0
 * @since 2023-05-30
 */
@Tag(name = "07.订单管理", description = "订单管理相关接口")
@RestController
@RequestMapping("/fcxs/order")
public class FcxsOrderController extends BaseValidController<
        FcxsOrderService,
        FcxsOrder,
        FcxsOrderQuery,
        FcxsOrderVO,
        FcxsOrderUVO
        > {
    @Autowired
    private FcxsOrderService fcxsOrderService;
    @Autowired
    private FcxsHouseService fcxsHouseService;

    @Autowired
    private FcxsPaymentPlanService fcxsPaymentPlanService;

    @Autowired
    private FcxsCustomerService fcxsCustomerervice;


    @Autowired
    private FcxsFinancialService fcxsFinancialService;
    @Autowired
    private FcxsDiscountService fcxsDiscountService;
    @Autowired
    private FcxsScheduleService fcxsScheduleService;

    @Override
    protected FcxsOrderService getBaseService() {
        return fcxsOrderService;
    }

    @Override
    protected MyLambdaQueryWrapper<FcxsOrder> queryWrapper(FcxsOrderQuery query) {
        MyLambdaQueryWrapper<FcxsOrder> queryWrapper = new MyLambdaQueryWrapper<>();
        queryWrapper.select(FcxsOrder::getId)
                .select(FcxsOrder::getOrderNo)
                .select(FcxsOrder::getCategory)
                .select(FcxsOrder::getCustomerId)
                .select(FcxsOrder::getHouseId)
                .select(FcxsOrder::getPrice)
                .select(FcxsOrder::getStatus)
                .select(FcxsOrder::getCreateDate)
                .select(FcxsOrder::getUpdateDate)
                .select(FcxsOrder::getContractDate)

                .organName(FcxsOrder::getOrganId).as("organ_name")
                .userName(FcxsOrder::getOperatorId).as("operator_name");
        queryWrapper.select("IFNULL((price-"+getTotal("discount")+"),0)-(" + getTotalFinancial(1)+"-"+getTotalFinancial(2) + ")").as("remaining_amount");
        queryWrapper.select(getTotal("discount")).as("discount_total");
        queryWrapper.select(getTotal("financial")).as("financial_total");
        queryWrapper.select(getTotal("payment_plan")).as("payment_plan_total");
        queryWrapper.select("IFNULL(" + getTotal("discount") + "+" + getTotal("financial") + "+" + getTotal("payment_plan") + ",0)").as("total_price");
     queryWrapper.select("(SELECT name FROM fcxs_customer WHERE id = customer_id AND deleted=0 LIMIT 1)").as("customer_name");
     queryWrapper.select("(SELECT phone FROM fcxs_customer WHERE id = customer_id AND deleted=0 LIMIT 1)").as("customer_phone");

        if (query != null) {
            queryWrapper.like(StringUtils.isNotBlank(query.getOrder_no()), FcxsOrder::getOrderNo, query.getOrder_no())
                    .eq(query.getCustomer_id() != null, FcxsOrder::getCustomerId, query.getCustomer_id())
                    .eq(query.getHouse_id() != null, FcxsOrder::getHouseId, query.getHouse_id())
                    .eq(query.getPay_mode() != null, FcxsOrder::getPayMode, query.getPay_mode())

                    .eq(query.getStatus() != null, FcxsOrder::getStatus, query.getStatus());
        }
        return queryWrapper;
    }

    @Override
    protected MyLambdaQueryWrapper<FcxsOrder> queryInfoWrapper() {
        MyLambdaQueryWrapper<FcxsOrder> queryWrapper = new MyLambdaQueryWrapper<>();
        queryWrapper.select(FcxsOrder::getId)
                .select(FcxsOrder::getOrderNo)
                .select(FcxsOrder::getCustomerId)
                .select(FcxsOrder::getCategory)
                .select(FcxsOrder::getOrganId)
                .select(FcxsOrder::getHouseId)
                .select(FcxsOrder::getPrice)
                .select(FcxsOrder::getContract)
                .select(FcxsOrder::getContractDate)
                .select(FcxsOrder::getPayMode)
                .select(FcxsOrder::getSubscription)
                .select(FcxsOrder::getRemark)
                .select(FcxsOrder::getStatus)

                .select(FcxsOrder::getCreateDate)
                .select(FcxsOrder::getUpdateDate)
                .organName(FcxsOrder::getOrganId).as("organ_name")
                .userName(FcxsOrder::getOperatorId).as("operator_name");
        return queryWrapper;
    }

    @Override
    protected FcxsOrder addValid(FcxsOrderVO entity) {

        FcxsOrder data = new FcxsOrder();
        BeanUtil.copyProperties(entity, data);
        String s = Utils.generateOrderNumber("DD");
        data.setOrderNo(s);
        FcxsHouse byId = fcxsHouseService.getById(data.getHouseId());
        if(byId == null){

       throw new RuntimeException("房源不存在");
        }
        data.setPrice(byId.getTotalPrice());
        return data;
    }

    @Override
    protected FcxsOrder editValid(FcxsOrderUVO entity) {
        if(entity.getHouseId() != null){
            FcxsOrder data = new FcxsOrder();
            BeanUtil.copyProperties(entity, data);
            FcxsHouse byId = fcxsHouseService.getById(data.getHouseId());
            if(byId == null){

                throw new RuntimeException("房源不存在");
            }
            data.setPrice(byId.getTotalPrice());

            return data;
        }
        return null;
    }

    @Operation(summary = "根据ID查询")
    @GetMapping("/{id}")
    public Result<Map<String, Object>> getById(@PathVariable Long id) {
        MyLambdaQueryWrapper<FcxsOrder> queryWrapper = queryInfoWrapper();
        queryWrapper.select(FcxsOrder::getCreateDate, FcxsOrder::getUpdateDate);
        queryWrapper.select(getTotal("discount")).as("discount_total");
        queryWrapper.select("IFNULL((price-"+getTotal("discount")+"),0)").as("payable_amount");
        queryWrapper.select("(" + getTotalFinancial(1)+"-"+getTotalFinancial(2) + ")").as("financial_total");
        queryWrapper.select("IFNULL((price-"+getTotal("discount")+"),0)-(" + getTotalFinancial(1)+"-"+getTotalFinancial(2) + ")").as("remaining_amount");
        queryWrapper.select(getTotal("payment_plan")).as("payment_plan_total");
        queryWrapper.select("IFNULL(" + getTotal("discount") + "+(" + getTotalFinancial(1)+"-"+getTotalFinancial(2) + ")+" + getTotal("payment_plan") + ",0)").as("total_price");
        queryWrapper.eq(FcxsOrder::getId, id);
        queryWrapper.last("limit 1");
        Map<String, Object> data = getBaseService().getMap(queryWrapper);
        if (data == null) {
            return Result.error(404, "数据不存在");
        }
        data.put("house", fcxsHouseService.findById((Long) data.get("house_id")));
        data.put("customer", fcxsCustomerervice.findById((Long) data.get("customer_id")));
        data.put("payment_plan", fcxsPaymentPlanService.findByOrderIdList(id));
        data.put("financial", fcxsFinancialService.findByOrderIdList(id));
        data.put("discount", fcxsDiscountService.findByOrderIdList(id));
        data.put("schedule", fcxsScheduleService.findByOrderIdList(id));


        return Result.ok(data);
    }

    private String getTotal(String tableName) {
        return "IFNULL((SELECT SUM(amt) FROM fcxs_" + tableName + " WHERE deleted=0 and order_id = fcxs_order.id),0)";
    }
    private String getTotalFinancial(int type) {
        return "IFNULL((SELECT SUM(amt) FROM fcxs_financial WHERE type = " + type + " AND deleted=0 and order_id = fcxs_order.id),0)";
    }
}
